<?php


namespace app\common\model;


use app\common\service\redis\PoolRedis;
use app\model\AdminDormitory;
use app\model\AdminSchoolRkeRecord;
use app\model\AdminStaff;
use app\model\AdminStaffActiveCount;
use app\model\AdminStaffData;
use app\model\AdminUserData;
use think\facade\Log;

class HomeStatisticsModel
{
    const STAFF_CACHE_KEY = 'staff_group:';
    const DOR_STAFF_CACHE_KEY = 'dor_staff_group:';

    // 首页获取用户构成数量, staff_group:{$school_id} {$sex}:{$type} 1
    public static function sexStructureAmount($school_id = 0)
    {
        // '男:0' => [
        //    'name' => '学生(男)',
        //    'value' => 0
        // ]
        $columnList = [];
        foreach (AdminStaff::TYPE_ARR as $type => $item) {
            foreach (['男','女'] as $sex) {
                $columnList["{$sex}:{$type}"] = [
                    'name' => "{$item}({$sex})",
                    'value' => 0
                ];
            }
        }
        $redis = PoolRedis::instance();
        $countKey = AdminStaff::SCHOOL_SEX_GROUP;
        $cache_keys = PoolRedis::scanAllForMatch($countKey."*");
        // 未缓存用户构成数量
        if (!$cache_keys || count($cache_keys) == 0) {
            AdminStaff::setAmountBySchool();
        }
        if ($school_id > 0) {
            $cache_keys = [$countKey.$school_id];
        }
        foreach ($cache_keys as $key) {
            $list = $redis->hGetAll($key);
            foreach ($list as $index => $item) {
                    $columnList[trim($index)]['value'] += intval($item);
            }
        }
        return array_values($columnList);
    }

    // 宿舍楼用户统计,仅包含学生，dor_staff_group:user_count_{dormitory_id} field value
    public static function dorUserCount($school_id = 0)
    {
        $redis = PoolRedis::instance();
        $columnList = [];

        // 未缓存宿舍楼用户统计
        if (!AdminDormitory::notExistAndSetAllByUser()) {
            return $columnList;
        }
        $dormitoryIds = AdminDormitory::getDorSimpleList($school_id);
        $countKey = AdminDormitory::DORMITORY_COUNT_CACHE_KEY."user_count_";
        foreach ($dormitoryIds as $id) {
            $column['value'] = $redis->hGet($countKey.$id, 'value') ?: 0;
            $column['name'] = $redis->hGet($countKey.$id, 'name');
            array_push($columnList, $column);
        }
        unset($column);
        return array_values($columnList);
    }

    // todo 用户活跃统计,从数据库查找，待优化
    public static function userActiveCount($school_id = 0, $dormitory_id = 0, $date_type = 1)
    {
        $columnList = AdminStaffData::groupTime(2);

        $obj = (new AdminStaffActiveCount());
        switch ($date_type) {
            case 2: // 昨天
                $obj = $obj->where('day', date("Y-m-d", strtotime("-1 day")));
                break;
            case 3: // 近7天
                $obj = $obj->where('day', 'between',[date("Y-m-d", strtotime("-7 day")), date("Y-m-d")]);
                break;
            default: // 今天
                $obj = $obj->where('day', date('Y-m-d'));
                break;
        }
        if ($school_id > 0) {
            $obj = $obj->where('school_id', $school_id);
        }
        if ($dormitory_id > 0) {
            $obj = $obj->where('dormitory_id', $dormitory_id);
        }
        $list = $obj->field('hour_index,sex,sum(count) as total')
            ->group('hour_index,sex')->select()->toArray();
        foreach ($list as $item) {
            if ($item['sex'] == '男') {
                $columnList[$item['hour_index']]['man'] += $item['total'];
            } else {
                $columnList[$item['hour_index']]['woman'] += $item['total'];
            }
        }
        $data = [
            'label' => array_column($columnList, 'label'),
            'man' => array_column($columnList, 'man'),
            'woman' => array_column($columnList, 'woman'),
        ];
        $max = max(max($data['man']),max($data['woman']));
        $data['max'] = str_pad(1, strlen((string)$max) + 1,"0",STR_PAD_RIGHT);
        return $data;
    }

    // 宿舍楼今日开锁次数统计，dor_staff_group:unlock_count{Ymd}_{$dormitory_id} field value
    public static function dorUnlockCount($school_id = 0)
    {
        $redis = PoolRedis::instance();
        $columnList = [
            'value' => [],
            'label' => []
        ];
        $dormitoryIds = AdminDormitory::getDorSimpleList($school_id);

        $countKey = AdminDormitory::DORMITORY_COUNT_CACHE_KEY."unlock_count:".date('Y-m-d')."_";
        $keys = PoolRedis::scanAllForMatch($countKey."*");
        // 未缓存开锁统计次数
        if (!$keys || count($keys) == 0) {
            $list = AdminDormitory::where('is_delete', 0)
                ->withCount(['unlock' => function ($query, &$alias) {
                    $query->whereDay('create_time');
                    $alias = 'value';
            }])->select()->toArray();
            $redis->multi(\Redis::PIPELINE);
            foreach ($list as $item) {
                $redis->hSet($countKey.$item['id'], 'value', $item['value']);
                $redis->hSet($countKey.$item['id'], 'name', $item['name']);
                $redis->expire($countKey.$item['id'], 1*24*60*60);
            }
            $redis->exec();
        }
        foreach ($dormitoryIds as $id) {
            $columnList['value'][] = $redis->hGet($countKey.$id, 'value');
            $columnList['label'][] = $redis->hGet($countKey.$id, 'name');
        }
        return $columnList;
    }
    // 获取今日门禁开锁次数统计 key => school_rke_unlock_count:{Ymd}_{school_id}
    public static function rkeUnlockCount($school_id = 0, $sex = null)
    {
        $columnList = AdminSchoolRkeRecord::groupTime(3, 24);
        $redis = PoolRedis::instance();

        $countKey = AdminSchoolRkeRecord::SCHOOL_RKE_RECORD_KEY.date('Y-m-d')."_";
        $keys = PoolRedis::scanAllForMatch($countKey."*");
        // 未缓存门禁开锁统计次数
        if (!$keys || count($keys) == 0) {
            AdminSchoolRkeRecord::addRkeRecode();
        }
        if ($school_id) {
            $keys = [$countKey.$school_id];
        }
        foreach ($keys as $key) {
            $hour_list = $redis->hGetAll($key);
            foreach ($hour_list as $index => $item) {
                $hour = explode(":", $index);
                if ($sex && $hour[0] != $sex) {
                    continue;
                }
                $columnList[$hour[1]]['value'] += intval($item);
            }
        }
        return [
            'label' => array_column($columnList, 'label'),
            'value' => array_column($columnList, 'value')
        ];
    }


}